package com.example.shellcollector;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import androidx.transition.TransitionInflater;


import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.shellcollector.service.AppInstalledCollectService;
import com.example.shellcollector.service.AppUsageCollectService;
import com.example.shellcollector.util.AppUsageCollectHelper;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.TimeZone;

public class SettingsFragment extends Fragment {

    static final String TAG = "SettingsFragment";

    public static class PrefsFragement extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.preferences_setting, rootKey);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


            Preference pstart = findPreference("set_start_time");
            Preference pend = findPreference("set_end_time");

            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);


            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
            SharedPreferences.Editor editor = sharedPreferences.edit();

            // 判断是否应用程序被销毁
            long test1 = sharedPreferences.getLong("start", 0);
            if (test1 != 0) {
                pstart.setSummary(sdf.format(test1));
            }

            long test2 = sharedPreferences.getLong("end", 0);
            if (test1 != 0 && test2 != 0) {
                pend.setSummary(sdf.format(test2));
            } else {
                pend.setSummary("默认当前时间：" + sdf.format(date));

                editor.putLong("end", calendar.getTimeInMillis());
                editor.apply();
            }


            // 监听点击事件
            pstart.setOnPreferenceClickListener(preference -> {
                openDatePicker(preference.getKey());
                return true;
            });
            pend.setOnPreferenceClickListener(preference -> {
                openDatePicker(preference.getKey());
                return true;
            });
        }

        private void updatePreference(String key, long result, Date date) {
            Preference preference = findPreference(key);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
            SharedPreferences.Editor editor = sharedPreferences.edit();
            if (preference != null) {
                if (key.equals("set_start_time")) {
                    preference.setSummary("起始时间为：" + sdf.format(date));

                    editor.putLong("start", result);
                }
                if (key.equals("set_end_time")) {
                    preference.setSummary("结束时间为：" + sdf.format(date));

                    editor.putLong("end", result);
                }

                editor.apply();
            }
        }

        private void openDatePicker(String key) {


            Calendar selectedDate = Calendar.getInstance();
            Date sd = new Date();
            selectedDate.setTime(sd);

            Calendar startDate = Calendar.getInstance();
            startDate.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH)-10);

            Calendar endDate = Calendar.getInstance();
            endDate.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH));


            TimePickerView pickerView = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {

                    // 此时date为GMT+0的12:00左右（GMT+8的20:00左右）
                    // 我们想得到这一天00:00的时间戳，直接去尾就可以
                    // 转换时区的工作在`AppUsageCollectHelper.getStartTimeOfDayLocal`中做了

                    Log.i("pvTime", "onTimeSelect");

                    Calendar confirmDate = Calendar.getInstance();

                    confirmDate.setTime(date);


                    long result = confirmDate.getTimeInMillis();
                    //result = AppUsageCollectHelper.getStartTimeOfDayLocal(result);

                    updatePreference(key, result, date);

                }

            })
                    .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                        @Override
                        public void onTimeSelectChanged(Date date) {
                            Log.i("pvTime", "onTimeSelectChanged");
                        }
                    })
                    .setCancelText("取消")
                    .setSubmitText("确认")
                    .setDate(selectedDate)
                    .setRangDate(startDate, endDate)
                    .setContentTextSize(18)
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("年", "月", "日", "时", "分", "秒")
                    .isDialog(true)
                    .addOnCancelClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.i("pvTime", "onCancelClickListener");
                        }
                    })

                    .setItemVisibleCount(5)
                    .setLineSpacingMultiplier(2.0f)
                    .setTextXOffset(40, 0, -40, 0, 0, 0)
                    .isAlphaGradient(true)
                    .isCenterLabel(false)
                    .build();
            Dialog mDialog = pickerView.getDialog();
            if (mDialog != null) {
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        Gravity.BOTTOM
                );
                params.leftMargin = 0;
                params.rightMargin = 0;
                pickerView.getDialogContainerLayout().setLayoutParams(params);

                Window dialogWindow = mDialog.getWindow();
                if (dialogWindow != null) {
                    //dialogWindow.setWindowAnimations();
                    dialogWindow.setGravity(Gravity.BOTTOM);
                    dialogWindow.setDimAmount(0.3f);
                }
            }
            pickerView.show();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TransitionInflater inflater = TransitionInflater.from(requireContext());
        setEnterTransition(inflater.inflateTransition(R.transition.fade));
        setExitTransition(inflater.inflateTransition(R.transition.fade));
        getActivity()
                .getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_layout, new PrefsFragement())
                .commit();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_settings, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        @SuppressLint("UseRequireInsteadOfGet") Button startBtn = Objects.requireNonNull(getView()).findViewById(R.id.start_usage_collect);
        @SuppressLint("UseRequireInsteadOfGet") Button stopBtn = Objects.requireNonNull(getView()).findViewById(R.id.stop_usage_collect);

        startBtn.setOnClickListener(v -> {
            if (getActivity() != null) {
                Intent intent1 = new Intent(getActivity(), AppUsageCollectService.class);
                Intent intent2 = new Intent(getActivity(), AppInstalledCollectService.class);
                getActivity().startService(intent1);
                getActivity().startService(intent2);
            }
        });

        stopBtn.setOnClickListener(v -> {
            if (getActivity() != null) {
                Intent intent1 = new Intent(getActivity(), AppUsageCollectService.class);
                Intent intent2 = new Intent(getActivity(), AppInstalledCollectService.class);
                getActivity().stopService(intent1);
                getActivity().stopService(intent2);
            }
        });
    }


}
